//
//  RegisterViewController.m
//  zhiche--delivery
//
//  Created by LeeBruce on 16/6/12.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "RegisterViewController.h"
#import "TopBackView.h"
#import "Common.h"
#import "WKProgressHUD.h"
#import "ProtocolViewController.h"
#import "SSKeychain.h"
#import "Header.h"

@interface RegisterViewController ()<UITextFieldDelegate>

@property (nonatomic,strong) UITextField *phoneTextField;
@property (nonatomic,strong) UITextField *captchaTextField;
@property (nonatomic,strong) UITextField *passwordField;
@property (nonatomic,strong) UITextField *adviceField;


@property (nonatomic,strong) UIButton *captchaButton;
@property (nonatomic) NSInteger secondCountDown;

@property (nonatomic) NSInteger integer1;
@property (nonatomic) NSInteger integer2;
@property (nonatomic) BOOL isAgree;

@property (nonatomic,strong) UIScrollView *scrollV;

@property (nonatomic,strong) WKProgressHUD *hud;

@property (nonatomic,copy) NSString *uuidString;



@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    TopBackView *topBackView= [[TopBackView alloc]initViewWithFrame:CGRectMake(0, 0, screenWidth, 64) andTitle:@"慧运车"];
    topBackView.rightButton.hidden = YES;
    [topBackView.leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:topBackView];
    
    self.view.backgroundColor = WhiteColor;
    
    [self initSubViews];
    
    _isAgree = NO;

}

-(void)initSubViews
{
    
    self.scrollV = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, screenWidth, screenHeight + 1)];
    self.scrollV.contentSize = CGSizeMake(screenWidth, screenHeight + 1);
    [self.view addSubview:self.scrollV];
    
    UIImageView *logoImageV = [[UIImageView alloc]initWithFrame:CGRectMake((screenWidth - 108)/2.0,  55 * kHeight, 108, 40)];
    logoImageV.image = [UIImage imageNamed:@"register_logo"];
    
    [self.scrollV addSubview:logoImageV];

    self.phoneTextField = [[UITextField alloc]init];
    self.phoneTextField.placeholder = @"请输入手机号";
    self.phoneTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    self.captchaTextField = [[UITextField alloc]init];
    self.captchaTextField.placeholder = @"请输入验证码";
    self.captchaTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    self.passwordField = [[UITextField alloc]init];
    self.passwordField.placeholder = @"请输入6-14位数字与字母组合的密码";
    self.passwordField.secureTextEntry = YES;
    self.passwordField.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    self.adviceField = [[UITextField alloc]init];
    self.adviceField.placeholder = @"请输入邀请码(选填)";
    self.adviceField.clearButtonMode = UITextFieldViewModeWhileEditing;

    //手机号
    UIView *firstV = [self backViewWithFloat:(CGRectGetMaxY(logoImageV.frame) + 28 * kHeight ) andField:self.phoneTextField  andImage:[UIImage imageNamed:@"register_phone"]];
    
    [self.scrollV addSubview:firstV];
    
    //验证码
    UIView *secondV = [self backViewWithFloat:CGRectGetMaxY(firstV.frame) andField:self.captchaTextField  andImage:[UIImage imageNamed:@"register_capture"]];
    
    [self.scrollV addSubview:secondV];
    
    
    //密码
    UIView *thirdV = [self backViewWithFloat:CGRectGetMaxY(secondV.frame) andField:self.passwordField andImage:[UIImage imageNamed:@"register_password"]];
    
    [self.scrollV addSubview:thirdV];
    thirdV.tag = 300;

    
    //邀请码
//    UIView *fourthV = [self backViewWithFloat:CGRectGetMaxY(thirdV.frame) andField:self.adviceField andImage:[UIImage imageNamed:@"register_adivice"]];
//    [self.scrollV addSubview:fourthV];
//    fourthV.tag = 300;
    
    
    //获取验证吗
    self.captchaButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    self.captchaButton.frame = CGRectMake(screenWidth - 100 * kWidth, (cellHeight - 23 * kHeight)/2.0, 75 * kWidth, 23 * kHeight);
    [self.captchaButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.captchaButton setTitleColor:YellowColor forState:UIControlStateNormal];
    self.captchaButton.backgroundColor = Color_RGB(253, 243, 232, 1);
    [self.captchaButton addTarget:self action:@selector(captchaButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.captchaButton.titleLabel.font = Font(12);
    self.captchaButton.layer.cornerRadius = 5;
    self.captchaButton.layer.borderColor = YellowColor.CGColor;
    self.captchaButton.layer.borderWidth = 0.5;
    
    [firstV addSubview:self.captchaButton];
    
    
    
    //注册
    UIButton *registerButton = [UIButton buttonWithType:UIButtonTypeCustom];
    registerButton.frame = CGRectMake(18 , CGRectGetMaxY(thirdV.frame) + 30 * kHeight, screenWidth - 36, Button_height);
    registerButton.backgroundColor = YellowColor ;
    [registerButton setTitle:@"注 册" forState:UIControlStateNormal];
    [registerButton setTitleColor:WhiteColor forState:UIControlStateNormal];
    [registerButton addTarget:self action:@selector(registerButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
    registerButton.layer.cornerRadius = 5 * kWidth;
    registerButton.titleLabel.font = Font(15);
    
    [self.scrollV addSubview:registerButton];


    /*
    
    UIButton *agreeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    agreeButton.frame = CGRectMake(CGRectGetMinX(registerButton.frame), CGRectGetMaxY(registerButton.frame) + 14, 14.5, 14.5);
    agreeButton.tag = 500;
    
    [agreeButton setBackgroundImage:[UIImage imageNamed:@"regist_unselected"] forState:UIControlStateNormal];
    [agreeButton setBackgroundImage:[UIImage imageNamed:@"regist_selected"] forState:UIControlStateSelected];
    [agreeButton addTarget:self action:@selector(agreeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    agreeButton.layer.borderColor = YellowColor.CGColor;
    [self.scrollV addSubview:agreeButton];
    
    UILabel *agreeL = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(agreeButton.frame) + 5, CGRectGetMidY(agreeButton.frame) - 10, 50, 20)];
    agreeL.text = @"已阅读";
    agreeL.textColor = littleBlackColor;
    agreeL.font = Font(12);
    [self.scrollV addSubview:agreeL];
    
    UIButton *bigBut = [UIButton buttonWithType:UIButtonTypeCustom];
    bigBut.frame = CGRectMake(CGRectGetMinX(agreeButton.frame ), CGRectGetMinY(agreeButton.frame), 55, 30);
    [self.scrollV addSubview:bigBut];
    [bigBut addTarget:self action:@selector(bigBut) forControlEvents:UIControlEventTouchUpInside];

    
    //协议按钮
    UIButton *protocolButton = [self backButtonWithString:@"《用户协议》" andFont:12 andFrame:CGRectMake(CGRectGetMaxX(agreeL.frame), CGRectGetMidY(agreeL.frame) - 10, 72 * kWidth, 20)];
    [protocolButton addTarget:self action:@selector(protocolButton) forControlEvents:UIControlEventTouchUpInside];
    protocolButton.tag = 300;
    [protocolButton setTitleColor:YellowColor forState:UIControlStateNormal];
    
    [self.scrollV addSubview:protocolButton];
    
    
    
    self.phoneTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    self.captchaTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    

    */
    

    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap)];
    [self.scrollV addGestureRecognizer:tap];

 
}


-(void)bigBut
{
    UIButton *button = (UIButton *)[self.view viewWithTag:500];
    [self agreeButtonAction:button];
}

-(void)agreeButtonAction:(UIButton *)sender
{
    sender.selected = !sender.selected;
    if (sender.selected) {
        _isAgree = YES;
    } else {
        _isAgree = NO;
    }
    
}
#pragma mark 协议方法

-(void)protocolButton
{
    ProtocolViewController *protocolV = [[ProtocolViewController alloc]init];
    
    [self.navigationController pushViewController:protocolV animated:YES];
}
#pragma mark 注册方法

-(void)registerButtonAction
{
    
    //获取uuid
    [self sendUUID];

    
    //先判断手机号的正确
    NSString *regExp = @"^[1]([3][0-9]|[8][0-9]|[5][0-9]|45|47|76|77|78)[0-9]{8}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regExp];
    BOOL isRight = [pred evaluateWithObject:self.phoneTextField.text];
    
    if (isRight) {

        self.hud = [WKProgressHUD showInView:self.view withText:@"" animated:YES];
        
//    if (_isAgree) {
        
          NSString *string = [NSString stringWithFormat:@"%@",self.adviceField.text];
        if ([string isEqual:[NSNull null]]) {
            string = @"";
        }
    
          NSDictionary *dic = @{@"phone":self.phoneTextField.text,
                                @"code":self.captchaTextField.text,
                                @"uuid":self.uuidString,
                                @"usertype":userType,
                                @"password":self.passwordField.text,
                                @"invitedcode":string};
    
    
          Common *c = [[Common alloc]init];
          [c afPostRequestWithUrlString:registers parms:dic finishedBlock:^(id responseObj) {
    
              [self.hud dismiss:YES];
              
              NSDictionary *dictonary = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
              
              [WKProgressHUD popMessage:dictonary[@"message"] inView:self.view duration:1.5 animated:YES];

    
              if ([[dictonary objectForKey:@"success"] boolValue]) {
    
                  
                  NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                  [userDefaults setObject:@"login" forKey:@"login"];
                  
                  [userDefaults setObject:dictonary[@"data"][@"Authorization"] forKey:login_token];

    
       //延迟执行
           dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
//                 [self.navigationController popViewControllerAnimated:YES];
               
               [self dismissViewControllerAnimated:YES completion:nil];
        
             });
              } else {
                 
                  [WKProgressHUD popMessage:dictonary[@"message"] inView:self.view duration:1.5 animated:YES];

              }
    
    
          } failedBlock:^(NSString *errorMsg) {
              
              [self.hud dismiss:YES];
              NSLog(@"%@",errorMsg);
          }];
    
//    } else {
//        
//        [WKProgressHUD popMessage:@"请先阅读并同意协议" inView:self.view duration:1.5 animated:YES];
//
//    }
    } else {
        [WKProgressHUD popMessage:@"请输入正确的手机号" inView:self.view duration:1.5 animated:YES];

    }
    
    
}


-(void)showAlertControllerWithString:(NSString *)string
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:string message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:action1];
    [alertController addAction:action2];
    
    [self presentViewController:alertController animated:YES completion:nil];
    
    
    
}



-(UIButton *)backButtonWithString:(NSString *)title andFont:(NSInteger)integer andFrame:(CGRect)frame
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = frame;
    [button setTitle:title forState:UIControlStateNormal];
    button.titleLabel.font = Font(12);
    [button setTitleColor:BlackColor forState:UIControlStateNormal];
    
    return button;
}

#pragma mark 验证码方法
-(void)captchaButtonAction:(UIButton *)sender
{
    
        //先判断手机号的正确
        NSString *regExp = @"^[1]([3][0-9]|[8][0-9]|[5][0-9]|45|47|76|77|78)[0-9]{8}$";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regExp];
        BOOL isRight = [pred evaluateWithObject:self.phoneTextField.text];
    
        if (isRight) {
    
       
            NSDictionary *dic = @{@"phone":self.phoneTextField.text,
                                  @"usertype":userType};
                           
    
            Common *c = [[Common alloc]init];
            
      [c afPostRequestWithUrlString:get_capture parms:dic finishedBlock:^(id responseObj) {
          
          NSDictionary *diction = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
          
          [WKProgressHUD popMessage:diction[@"message"] inView:self.view duration:1.5 animated:YES];
          
          if ([diction[@"success"] boolValue]) {
              
              [sender setTintColor:YellowColor];
              sender.userInteractionEnabled = NO;
              _secondCountDown = 60;
              NSTimer *time = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireAction:) userInfo:nil repeats:YES];
              [time fire];

          }

      } failedBlock:^(NSString *errorMsg) {
          NSLog(@"%@",errorMsg);
      }];
            
        } else {
            
            [WKProgressHUD popMessage:@"手机号码不正确，请重新输入" inView:self.view duration:1.5 animated:YES];

            
        }
}

-(void)timeFireAction:(NSTimer *)time
{
    _secondCountDown --;
    
    //设置button下划线
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"(%zis)",_secondCountDown]];
    NSRange strRange = {0,[str length]};
    [str addAttribute:NSForegroundColorAttributeName value:YellowColor range:strRange];  //设置颜色
    [self.captchaButton setAttributedTitle:str forState:UIControlStateNormal];
    
    
    if (_secondCountDown <= 0) {
        [time invalidate];
        self.captchaButton.userInteractionEnabled = YES;
        //设置button下划线
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"重新发送"];
        NSRange strRange = {0,[str length]};
        [str addAttribute:NSForegroundColorAttributeName value:YellowColor range:strRange];  //设置颜色
//        [str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:strRange];
        
        [self.captchaButton setAttributedTitle:str forState:UIControlStateNormal];
        
    }
}


#pragma mark UITextFieldDelegate
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string isEqualToString:@"\n"]) {
        [textField resignFirstResponder];
        return NO;
    }
    return YES;
}



-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    
    [UIView animateWithDuration:0.3 animations:^{
        /* 计算偏移量 */
        
        CGFloat height = 268;
        UIView *view = (UIView *)[self.view viewWithTag:300];
        CGFloat offsetHeight = CGRectGetMaxY(view.frame) - (Main_height - height- 64);
        
        
        if (offsetHeight > 0) {
            self.scrollV.contentInset = UIEdgeInsetsMake(-offsetHeight , 0, 0, 0);
            
        }
        
    } completion:^(BOOL finished) {
        
    }];
    
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [UIView animateWithDuration:0.3 animations:^{
        
        self.scrollV.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        
    }];
}



-(void)tap
{
    [self.view endEditing:YES];
}

-(UIView *)backViewWithFloat:(CGFloat)y andField:(UITextField *)textField andImage:(UIImage *)image
{
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, y, screenWidth, cellHeight)];
    
    CGSize size = CGSizeMake(image.size.width, image.size.height);
    UIImageView *imaV = [[UIImageView alloc]initWithImage:image];
    imaV.frame = CGRectMake(28 * kWidth, (cellHeight - size.height)/2.0, size.width, size.height);
    [view addSubview:imaV];
    
    textField.frame = CGRectMake(CGRectGetMaxX(imaV.frame) + 17, 0, screenWidth - 100, view.frame.size.height);
    textField.font = Font(13);
    [view addSubview:textField];
    textField.delegate = self;
    textField.returnKeyType = UIReturnKeyDone;

    
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, view.frame.size.height - 0.5, screenWidth - 20, 0.5)];
    [view addSubview:label];
    label.backgroundColor = LineGrayColor;
    
    return  view;
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appGoForeground:) name:@"foreground" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appGoBackground:) name:@"background" object:nil];
    
    
}

- (void)appGoBackground:(NSNotification *)notification
{
    
    _integer1 = [notification.userInfo[@"time"] integerValue];
    
}

- (void)appGoForeground:(NSNotification *)notification
{
    NSInteger integer = [notification.userInfo[@"time"] integerValue];
    
    _integer2 = (integer - _integer1)/1000;
    
    _secondCountDown = _secondCountDown - _integer2;
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}


-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
//    [self dismissViewControllerAnimated:YES completion:nil];
}


-(void)sendUUID{
    //    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    CFUUIDRef uuid = CFUUIDCreate(NULL);
    assert(uuid != NULL);
    CFStringRef uuidStr = CFUUIDCreateString(NULL, uuid);
    if (![SSKeychain passwordForService:@"com.sandwish.eduOnline" account:@"user"]) {//查看本地是否存储指定 serviceName 和 account 的密码
        
        [SSKeychain setPassword: [NSString stringWithFormat:@"%@", uuidStr]
                     forService:@"com.sandwish.eduOnline"account:@"user"];
        //从钥匙串读取UUID：
        NSString *retrieveuuid = [SSKeychain passwordForService:@"com.sandwish.eduOnline"account:@"user" ];
        //                NSLog(@"%@",retrieveuuid);
        //       NSLog(@"SSKeychain存储显示 :第一次安装过:%@", retrieveuuid);
        
        NSLog(@"%@",retrieveuuid);
        
        //        NSDictionary *parameters = @{@"token":retrieveuuid,@"phoneType":@"iphone"};
        
        self.uuidString = [NSString stringWithFormat:@"%@",retrieveuuid];
        
        //        NSLog(@"%@",parameters);
        //        [manager POST:postuuid parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
        //            //        NSLog(@"%@",responseObject);
        //        } failure:^(NSURLSessionDataTask *task, NSError *error) {
        //
        //        }];
        
    }else{
        
        //曾经安装过 则直接能打印出密码信息(即使删除了程序 再次安装也会打印密码信息) 区别于 NSUSerDefault
        
        
        //从钥匙串读取UUID：
        NSString *retrieveuuid = [SSKeychain passwordForService:@"com.sandwish.eduOnline"account:@"user"];
        NSLog(@"SSKeychain存储显示 :已安装过:%@", retrieveuuid);
        
        self.uuidString = [NSString stringWithFormat:@"%@",retrieveuuid];
        
        //        NSDictionary *parameters = @{@"token":retrieveuuid,@"phoneType":@"iphone"};
        //        NSLog(@"%@",parameters);
        //        [manager POST:postuuid parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
        //            //        NSLog(@"%@",responseObject);
        //        } failure:^(NSURLSessionDataTask *task, NSError *error) {
        //
        //        }];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
